import time
import datetime

from rest_framework import viewsets, mixins
from rest_framework.response import Response

from cart.models import CartModel
from goods.models import Foods
from orders.models import OrderPModel, OrderDetailModel, OrderFoodModel, PayModel, OrderCommentModel
from orders.serializers import OrderPSerializer, OrderFoodSerializer, OrderCommentSerializer, PaySerializer

from django.db.models import Q

from shops.models import ShopsModel, ShopActivityModel, CouponModel
from user.models import UserModel, UserAddressModel


class OrderPView(viewsets.GenericViewSet,
                 mixins.RetrieveModelMixin,
                 mixins.CreateModelMixin):

    queryset = OrderPModel.objects.all()
    serializer_class = OrderPSerializer

    def get_object(self):
        return OrderPModel.objects.filter(user_id=self.kwargs.pop('pk')).all()

    def create(self, request, *args, **kwargs):
        user_id = request.data.get('user_id')
        shop_id = request.data.get('shop_id')
        address_id = request.data.get('address_id')
        coupon_id = request.data.get('coupon_id') if 'coupon_id' in request.data else None
        remark = request.data.get('remark') if 'remark' else ''

        carts = CartModel.objects.filter(Q(user_id=user_id), Q(shop_id=shop_id)).all()
        if len(carts):
            order_number = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())))+ str(time.time()).replace('.', '')[-7:]
            total_number = 0
            foods_price = 0
            shop = ShopsModel.objects.filter(shop_id=shop_id).first()
            user = UserModel.objects.filter(user_id=user_id).first()
            box_cost = shop.box_cost
            for cart in carts:
                food_id = cart.food_id
                food = Foods.objects.filter(food_id=food_id).first()
                foods_price += cart.number * food.shell_price
                total_number += cart.number

            box_costs = box_cost * total_number
            total_price = box_costs + foods_price
            shop_activity = ShopActivityModel.objects.filter(Q(shop_id=shop_id), Q(target__lte=total_price)).order_by('-target').first()
            cut = shop_activity.cut if shop_activity else 0
            total_price -= cut

            if coupon_id:
                coupon = CouponModel.objects.filter(coupon_id=coupon_id).first()
                coupon_money = coupon.discount_money
                total_price -= coupon_money
            else:
                coupon_money = None

            now = datetime.datetime.now()
            demand_time = (now + datetime.timedelta(minutes=15))

            # 新建订单主表
            OrderPModel.objects.create(
                user_id=user_id,
                shop_id=shop_id,
                order_number=order_number,
                box_cost=box_costs,
                total_money=total_price,
                discount_money=cut,
                coupon_money=coupon_money,
                pay_money=total_price,
                created_time=now,
                demand_time=demand_time,
                remark=remark
            )

            # 新建订单详情
            address = UserAddressModel.objects.filter(address_id=address_id).first()
            order = OrderPModel.objects.filter(order_number=order_number).first()

            OrderDetailModel.objects.create(
                order_id=order.order_id,
                address_id=address_id,
                user_username=user.user_name,
                user_mobile=user.mobile,
                user_address=address.address,
                user_longitude=address.longitude,
                user_latitude=address.latitude,
                shop_shopname=shop.shop_name,
                shop_mobile=shop.shop_mobile,
                shop_address=shop.address,
                shop_longitude=shop.longitude,
                shop_latitude=shop.latitude
            )

            # 新建订单支付表
            PayModel.objects.create(
                shop_id=shop_id,
                user_id=user_id,
                order_id=order.order_id,
                total_money=total_price,
                status=1,
                created_time=now
            )

            # 新建订单商品表
            for cart in carts:
                food = Foods.objects.filter(food_id=cart.food_id).first()
                OrderFoodModel.objects.create(
                    order_id=order.order_id,
                    shop_id=shop_id,
                    shop_name=shop.shop_name,
                    food_id=cart.food_id,
                    food_name=food.food_name,
                    cover=food.cover,
                    origin_price=food.origin_price,
                    shell_price=food.shell_price,
                    number=cart.number
                )
                cart.delete()

            res = {'msg': '下单成功'}
        else:
            res = {'code': 1001, 'msg': '没有下单的商品，请添加'}

        return Response(res)

    def retrieve(self, request, *args, **kwargs):
        instances = self.get_object()
        serializer = self.get_serializer(instances, many=True)

        data = serializer.data
        res = {
            'data': data
        }
        return Response(res)


class OrderCommentView(viewsets.GenericViewSet,
                       mixins.CreateModelMixin):

    queryset = OrderCommentModel.objects.all()
    serializer_class = OrderCommentSerializer

    def create(self, request, *args, **kwargs):
        order_id = request.data.get('order_id')
        user_id = request.data.get('user_id')
        content = request.data.get('content') if 'content' in request.data else ''
        score = request.data.get('score')

        OrderCommentModel.objects.create(
            user_id=user_id,
            order_id=order_id,
            content=content,
            score=score,
            created_time=datetime.datetime.now()
        )

        res = {'msg': '评论成功'}
        return Response(res)


class PayView(viewsets.GenericViewSet,
              mixins.UpdateModelMixin):

    queryset = PayModel.objects.all()
    serializer_class = PaySerializer

    def get_object(self):
        return PayModel.objects.filter(order_id=self.kwargs.pop('pk')).first()

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        data = {'status': request.data.get('status'),
                'deal_time': datetime.datetime.now()}
        serializer = self.get_serializer(instance, data=data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        res = {'msg': '支付状态更改成功'}
        return Response(res)


class OrderFoodView(viewsets.GenericViewSet,
                    mixins.RetrieveModelMixin):

    queryset = OrderFoodModel.objects.all()
    serializer_class = OrderFoodSerializer

    def get_object(self):
        return OrderFoodModel.objects.filter(order_id=self.kwargs.pop('pk')).all()

    def retrieve(self, request, *args, **kwargs):
        order_id = kwargs.pop('pk')
        instances = self.get_object()
        serializer = self.get_serializer(instances, many=True)

        order = OrderPModel.objects.filter(order_id=order_id).first()
        orderdetail = OrderDetailModel.objects.filter(order_id=order_id).first()

        order_list = [
            {
                'order_id': order.order_id,
                'box_costs': order.box_cost,
                'vip_money': order.discount_money + order.coupon_money,
                'total_money': order.total_money,
                'user_address': UserAddressModel.objects.filter(address_id=orderdetail.address_id).first().address,
                'order_created_time': order.created_time,
                'shop_shopname': ShopsModel.objects.filter(shop_id=order.shop_id).first().shop_name,
                'order_number': order.order_number,
                'shop_mobile': orderdetail.shop_mobile
            }
        ]

        foods_data = serializer.data

        res = {
            'foods_list': foods_data,
            'order_list': order_list
        }
        return Response(res)
